/**
 * Created by Administrator on 2017/10/17.
 */
//controllor文件夹主要是用来放置封装的方法
var mongoose = require('mongoose');
const DataModel = require('../models/news.model');
const Comment = require('../models/comment.model');

var async = require('async');

exports.create = function (req,res,next) {//创建
	const dataModel = new DataModel(req.body);

		console.log(dataModel);
		dataModel.save()//保存用户信息，并以json格式输出
		.then(data=>{
			res.json(data);//将data以json的形式传送  === res.send(json)
		});
}


exports.get = function(req,res,next){//查询
	var id = req.params.id;//?用的是req.query /用的是req.params  post用的是req.body
	DataModel.findById(id, function (err, data) {
	  res.json(data);
	})
}

exports.update = function(req,res,next){//修改
	const id = req.params.id;

	DataModel.findByIdAndUpdate(id, {$set: req.body}, {new:false})
	.then(data=>{
		res.json(data);
	})

}

exports.remove = function(req,res,next){//删除
	const id = req.params.id;

	DataModel.findByIdAndRemove(id,function(err,data){
		res.json(data);
	})
	
}


exports.list = function(req,res,next){//分页
	var page = (req.body.page) ? req.body.page : 1;
	var rows = (req.body.rows) ? req.body.rows : 5;

	var queryCondition = {};//查询条件
	// if(req.body.name && req.body.name.trim().length>0){
	// 	name = req.body.name;
	// 	queryCondition = {
	// 		"name" : new RegExp(name, 'i')
	// 	}
	// }

	if(req.body.cateId && req.body.cateId.trim().length>0){
		cateId = req.body.cateId;
		// Object.assign对象合并
		queryCondition = Object.assign(queryCondition,
			{
				cateId: cateId
			}
		)
	}

	DataModel.paginate(queryCondition, {sort: { _id : -1 }, page: parseInt(page), limit: parseInt(rows) }, function(err, result) {
	 	result.rows = result.docs;
	 	delete result.docs;
	 	res.json(result)
	});
	// DataModel.paginate(queryCondition, { page: parseInt(page), limit: parseInt(limit) }, function(err, result) {
	// 			 // 评论数获取参考代码
	// 		async.map(result.docs,function(news,done){ // callback修改成done

	// 			Comment.count({newsId: news._id},function(err,count){
	// 				if(err){
	// 					return;
	// 				}else{
	// 					news.commentCount = count;
	// 					done();
	// 				}
	// 			})

	// 		},function(err){
	// 			res.json(result)
	// 		})
	// });
   
}
